package com.atguigu.day03;

import com.atguigu.util.ClickEvent;
import com.atguigu.util.ClickSource;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

public class Example10 {
    public static void main(String[] args) {
        var env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new ClickSource())
                .keyBy(r -> r.username)
                .process(new KeyedProcessFunction<String, ClickEvent, String>() {
                    // key: url
                    // value: url-count
                    private MapState<String, Integer> urlCount;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        urlCount = getRuntimeContext().getMapState(
                                new MapStateDescriptor<String, Integer>(
                                        "url-count",
                                        Types.STRING, // key的泛型
                                        Types.INT     // value的泛型
                                )
                        );
                    }

                    @Override
                    public void processElement(ClickEvent clickEvent, Context context, Collector<String> out) throws Exception {
                        // processElement中操作的状态变量是输入数据的key所对应的状态变量
                        // 如果字典状态变量中不存在url这个key,说明当前用户是第一次访问这个url
                        if (!urlCount.contains(clickEvent.url)) {
                            urlCount.put(clickEvent.url, 1);
                        } else {
                            urlCount.put(clickEvent.url, urlCount.get(clickEvent.url) + 1);
                        }

                        // 用户名
                        var username = context.getCurrentKey();

                        var result = new StringBuilder();
                        result.append(username).append("的字典状态变量是： {\n");

                        for (var key : urlCount.keys()) {
                            result.append("  ").append(key).append(" : ").append(urlCount.get(key)).append("\n");
                        }

                        result.append("}");

                        out.collect(result.toString());
                    }
                })
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
